<?php
require_once dirname(__FILE__) . '/User.php';

class UsersModel {
	const NOT_CONFIRMED_ROLE = 1;
	const USER_ROLE = 2;
	const ADMIN_ROLE = 4;

	private static $k_user = 'user';
	private static $k_username = 'username';
	private static $k_first_name = 'first_name';
	private static $k_last_name = 'last_name';
	private static $k_email = 'email';
	private static $k_role = 'role';
	private static $k_house = 'house';
	private static $k_password = 'password';

	

	private $database = NULL;
	
	public function __construct(Database $db) {
			$this->database = $db;
	}
	
	public function addUser(User $user) {
		if ($this->UserExists($user->username)) {
			return false;
		}
				
		$sql = 'INSERT INTO `' . self::$k_user . '` (`' . self::$k_username . '`,`' . self::$k_first_name . '`, `' . self::$k_last_name . '`, `' . self::$k_email . '`, `' . self::$k_role . '`, `' . self::$k_house . '`, `' . self::$k_password . '`) VALUES (?, ?, ?, ?, ?, ?, ?)';
		$stmt = $this->database->prepare($sql);
		$stmt->bind_param("ssssiss", $user->username, $user->firstName, $user->lastName, $user->email, $user->role, $user->house, $user->password);
		$this->database->ExecuteNonQuery($stmt);
			   
		return true;
	}
	
	public function getUsers($username = null) {
		$stmt = null;
		$users = array();
		
		if ($username == null) {
			$sql = 'SELECT `' . self::$k_username . '`,`' . self::$k_first_name . '`, `' . self::$k_last_name . '`, `' . self::$k_email . '`, `' . self::$k_role . '`, `' . self::$k_house . '`, `' . self::$k_password . '` From `' . self::$k_user . '` ORDER BY `role`, `first_name`';
			$stmt = $this->database->prepare($sql);
		} else {
			$sql = 'SELECT `' . self::$k_username . '`,`' . self::$k_first_name . '`, `' . self::$k_last_name . '`, `' . self::$k_email . '`, `' . self::$k_role . '`, `' . self::$k_house . '`, `' . self::$k_password . '` From `' . self::$k_user . '` WHERE `username` = ?';
			$stmt = $this->database->prepare($sql);
			$stmt->bind_param('s', $username);
		}

		$stmt->execute();
    	$stmt->bind_result($username, $firstName, $lastName, $email, $role, $house, $password);
    	
    	while ($stmt->fetch()) {
    		$users[] = User::create($username, $firstName, $lastName, $email, $role, $house, $password);
    	}
				
		return $users;
	}

	public function getUser($username) {
		if ($username) {
			$user = $this->getUsers($username);
			if (isset($user[0])) {
				return $user[0];
			}
		}

		return null;
	}
	
	public function userExists($username) {
		$sql = 'SELECT EXISTS(SELECT * FROM `' . self::$k_user . '` WHERE `' . self::$k_username . '`=?)';
		$stmt = $this->database->prepare($sql);
		$stmt->bind_param("s", $username);
		$exists = $this->database->SelectOne($stmt);
		
		return $exists;
	}
	
	public function updateUser(User $user) {
		$oldUser = $this->getUser($user->username);

		$email = ($user->email) ? $user->email : $oldUser->email;
		$house = ($user->house) ? $user->house : $oldUser->house;
		$role = ($user->role) ? $user->role : $oldUser->role;
		$username = $user->username;
		
		$sql = 'UPDATE `' . self::$k_user . '` SET `' . self::$k_email . '` = ?, `' . self::$k_house . '` = ?, `' . self::$k_role . '` = ? WHERE `' . self::$k_username . '` = ?;';
		$stmt = $this->database->prepare($sql);
		$stmt->bind_param("ssss", $email, $house, $role, $username);
		$this->database->ExecuteNonQuery($stmt);
	}
	
	public function removeUser($username) {
		if ($this->UserExists($username)) {
			$sql = 'DELETE FROM `' . self::$k_user . '` WHERE `' . self::$k_username . '` =?;';
			$stmt = $this->database->prepare($sql);
			$stmt->bind_param("s", $username);
			$this->database->ExecuteNonQuery($stmt);
			return true;
		}
		return false;
	}
	
	public function test($lh) {
		$this->RemoveUser('testuser');
		
		if ($this->UserExists('testuser')) {
			echo 'Fel! Användare "testuser" bör inte finnas.';
			return false;
		}
		
		$user = User::create('testuser', 'Test User', 'pwd', 'testuser@example.com');
		
		$addSuccessfull = $this->AddUser($user);
		
		if (!$addSuccessfull) {
			echo 'Fel! Adduser returnerade false trots att användaren inte fanns sedan tidigare';
			return false;
		}
		
		$lh->DoLogout();
		$lh->DoLogin('testuser', 'pwd');
		
		if (!$lh->IsLoggedIn()) {
			echo 'Fel! Det gick inte att logga in den nyskapade användaren "testuser".';
			return false;
		}
		
		$this->UpdateUser('testuser', 'pwd', 'test' , 'New Full Name', 'pass');
		
		$lh->DoLogout();
		$lh->DoLogin('test', 'pass');
		
		if (!$lh->IsLoggedIn()) {
			echo 'Fel! Den uppdaterade användaren "test" kunde inte loggas in.';
			return false;
		}
		
		if (!$this->UserExists('test')) {
			echo 'Fel! Användare "test" bör nu finnas.';
			return false;
		}
		
		$removeSucessfull = $this->RemoveUser('test');
		
		if (!$removeSucessfull) {
			echo 'Fel! RemoveUser("test") returnerade false trots att användaren bör kunna raderas.';
			return false;
		}
		
		if ($this->UserExists('test')) {
			echo 'Fel! Användare "test" bör inte finnas längre.';
			return false;
		}
		
		return true;
	}
}